<?php 
class ControllerAccountLogin extends Controller {
	private $error = array();
	
	public function index() {
		// Login override for admin users
		if (!empty($this->request->get['token'])) {
			$this->customer->logout();
			
			$this->load->model('account/customer');
			
			$customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);
			
		 	if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
				$this->redirect($this->url->link('account/account', '', 'SSL')); 
			}
		}		
		
		if ($this->customer->isLogged()) {  
      		$this->redirect($this->url->link('account/account', '', 'SSL'));
    	}
	
    	$this->language->load('account/login');

    	$this->document->setTitle($this->language->get('heading_title'));
								
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			unset($this->session->data['guest']);
			
			// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
			if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], HTTP_SERVER) !== false || strpos($this->request->post['redirect'], HTTPS_SERVER) !== false)) {
				$this->redirect(str_replace('&amp;', '&', $this->request->post['redirect']));
			} else {
				$this->redirect($this->url->link('account/account', '', 'SSL')); 
			}
    	}  
		
      	$this->data['breadcrumbs'] = array();

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),       	
        	'separator' => false
      	);
  
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_account'),
			'href'      => $this->url->link('account/account', '', 'SSL'),
        	'separator' => $this->language->get('text_separator')
      	);
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_login'),
			'href'      => $this->url->link('account/login', '', 'SSL'),      	
        	'separator' => $this->language->get('text_separator')
      	);
				
    	$this->data['heading_title'] = $this->language->get('heading_title');

    	$this->data['text_new_customer'] = $this->language->get('text_new_customer');
    	$this->data['text_register'] = $this->language->get('text_register');
    	$this->data['text_register_account'] = $this->language->get('text_register_account');
		$this->data['text_returning_customer'] = $this->language->get('text_returning_customer');
		$this->data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
    	$this->data['text_forgotten'] = $this->language->get('text_forgotten');

    	$this->data['entry_email'] = $this->language->get('entry_email');
    	$this->data['entry_password'] = $this->language->get('entry_password');

    	$this->data['button_continue'] = $this->language->get('button_continue');
		$this->data['button_login'] = $this->language->get('button_login');
		$this->data['text_login_facebook'] = $this->language->get('text_login_facebook');

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
		$this->data['action'] = $this->url->link('account/login', '', 'SSL');
		$this->data['register'] = $this->url->link('account/register', '', 'SSL');
		$this->data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');

    	// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
		if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], HTTP_SERVER) !== false || strpos($this->request->post['redirect'], HTTPS_SERVER) !== false)) {
			$this->data['redirect'] = $this->request->post['redirect'];
		} elseif (isset($this->session->data['redirect'])) {
      		$this->data['redirect'] = $this->session->data['redirect'];
	  		
			unset($this->session->data['redirect']);		  	
    	} else {
			$this->data['redirect'] = '';
		}

		if (isset($this->session->data['success'])) {
    		$this->data['success'] = $this->session->data['success'];
    
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/login.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/account/login.tpl';
		} else {
			$this->template = 'default/template/account/login.tpl';
		}
		
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'	
		);
		
		$this->response->setOutput($this->render());
  	}
	
	public function facebook() {
		$json = array();
		
		if ($this->request->post['cmd'] == 'loginfb') {
			$uid = $this->request->post['uid'];
			$access_token = $this->request->post['access_token'];
			
			// set session bawaan facebook hahaha (e.g: 'fb_FB_APPID_access_token, fb_FB_APPID_user_id)
			$this->session->data['fb_'.FB_APPID.'_access_token'] = $access_token;
			$this->session->data['fb_'.FB_APPID.'_user_id'] = $uid;
			
			$this->load->model('account/customer');
			$customer_info = $this->model_account_customer->getCustomerByFBuid($uid);
			
			if ($customer_info) {
				if ($customer_info['status'] != 1) {
					$json = array('status' => 'failed', 'message' => 'Sorry, your account has been disabled.');
				} else {
					// login success hehehe
					$this->session->data['customer_id'] = $customer_info['customer_id'];
					
					if ($customer_info['cart'] && is_string($customer_info['cart'])) {
						$cart = unserialize($customer_info['cart']);
						
						foreach ($cart as $key => $value) {
							if (!array_key_exists($key, $this->session->data['cart'])) {
								$this->session->data['cart'][$key] = $value;
							} else {
								$this->session->data['cart'][$key] += $value;
							}
						}
					}
					
					if ($customer_info['wishlist'] && is_string($customer_info['wishlist'])) {
						if (!isset($this->session->data['wishlist'])) {
							$this->session->data['wishlist'] = array();
						}
						
						$wishlist = unserialize($customer_info['wishlist']);
					
						foreach ($wishlist as $product_id) {
							if (!in_array($product_id, $this->session->data['wishlist'])) {
								$this->session->data['wishlist'][] = $product_id;
							}
						}
					}
					
					$this->model_account_customer->updateFBAccessToken($access_token, $uid);
					
					$json = array('status' => 'success');
				}
			} else {
				// not register yet, so registered automatically
				$fburl = 'https://graph.facebook.com/me?fields=id,name,email,birthday&access_token=' . $access_token;
				$data = json_decode(file_get_contents($fburl), true);
				
				$data = array(
					'firstname'				=> $data['name'],
					'lastname'				=> '',
					'email'					=> '',
					'telephone'				=> '',
					'fax'					=> '',
					'password'				=> '',
					'newsletter'			=> '',
					'address_id'			=> '',
					'customer_group_id'		=> '',
					'ip'					=> $_SERVER['SERVER_ADDR'],
					'status'				=> 1,
					'approved'				=> 1,
					'token'					=> '',
					'date_added'			=> date('Y-m-d H:i:s'),
					
					'register_by'			=> 'facebook',
					'facebook_uid'			=> $uid,
					'facebook_access_token'	=> $access_token
				);
				$lastid = $this->model_account_customer->registerFacebook($data);
				
				$this->session->data['customer_id'] = $lastid;
				$this->session->data['cart'] = array();
				$this->session->data['wishlist'] = array();
				
				$json = array('status' => 'success');
				
				//$json = array('status' => 'failed', 'message' => 'Your facebook login is not registered. Please register.');
			}
		}
		
		$this->response->setOutput(json_encode($json));
	}
  
  	private function validate() {
    	if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
      		$this->error['warning'] = $this->language->get('error_login');
    	}
	
    	if (!$this->error) {
      		return true;
    	} else {
      		return false;
    	}  	
  	}
}
?>